package com.qf.leadnewsuser.service.impl;

import com.alibaba.nacos.common.utils.MD5Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.leadnewsuser.mapper.UserMapper;
import com.qf.leadnewsuser.service.UserService;
import com.qf.qfleadnewsmodel.commons.dtos.ResponseResult;
import com.qf.qfleadnewsmodel.enums.AppHttpCodeEnum;
import com.qf.qfleadnewsmodel.user.dtos.LoginDto;
import com.qf.qfleadnewsmodel.user.pojos.ApUser;
import com.qf.qfleadnewsutils.commons.AppJwtUtil;
import io.jsonwebtoken.Jwt;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, ApUser> implements UserService  {
    @Override
    public ResponseResult login(LoginDto loginDto) {

        String phone = loginDto.getPhone();
        String password = loginDto.getPassword();

        //支持游客模式登录
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(password)){
            //游客模式 -- 登录成功，token中的用户id用0表示
            HashMap map = new HashMap();
            String token = AppJwtUtil.getToken(0l);
            map.put("token",token);

            return ResponseResult.okResult(map);
        }else{
            //根据phone查询user对象
            LambdaQueryWrapper<ApUser> qw = Wrappers.lambdaQuery(ApUser.class).eq(ApUser::getPhone, phone);
            ApUser apUser = baseMapper.selectOne(qw);

            //判断是否存在
            if (apUser == null){
                //不存在
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PHONE_ERROR);
            }else{
                //存在 -- 将页面传递的密码+salt进行md5运算，将得到的密文和数据库的密文比对
                String salt = apUser.getSalt();
                //页面传递过来的明文密码加盐后进行md5运算
                String pwdMd5 = MD5Utils.encodeHexString((password + salt).getBytes(StandardCharsets.UTF_8));
                pwdMd5 = DigestUtils.md5DigestAsHex((password + salt).getBytes(StandardCharsets.UTF_8));

                if (!pwdMd5.equals(apUser.getPassword())){
                    //密码错误
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }

                //正确 -- 成功 （返回token + 用户信息）
                HashMap map = new HashMap();
                String token = AppJwtUtil.getToken(apUser.getId());
                map.put("token",token);

                //对敏感信息进行脱敏处理
                apUser.setPassword("");
                apUser.setSalt("");

                map.put("user",apUser);

                return ResponseResult.okResult(map);
            }
        }
    }
}
